/*###################################################################*
#
# MP (Mitchell Pell) Base - CrossPlatform Base Utilities.
# Copyright (C) 2014  Mitchell Pell
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
####################################################################*/

#ifndef BASE_SHARED_COLLECTION_H
#define BASE_SHARED_COLLECTION_H

#include "UsesCharArray.h"
#include "RecursiveLockingMutex.h"
#include <vector>
namespace mp_base{
	namespace interfaces{

		/*!----------------------------------------------------------------
		*	@class		Collection
		*	@brief		Wrapper class for a vector array using a template
		*
		*	@author		Mitchell Pell
		*	@date		9/27/2013
		*	@version	1.0
		*
		-----------------------------------------------------------------*/
		template <class Item>
		class SharedCollection : public RecursiveLockingMutex
		{
		public:

			SharedCollection(){}
			SharedCollection(char* data){}

			virtual ~SharedCollection(){}

			void push_back(Item item){while(!TryLock()){;;}
				m_collection.push_back(item); Unlock();}

			Item pop_back(){Item tmp; while(!TryLock()){;;}
				= m_collection.pop_back(); Unlock(); return tmp;}

			void killgore(){}

			void erase(typename std::vector<Item>::iterator it)
				{m_collection.erase(it); }

			// -- Below require external lock

			bool TryLock(){return RecursiveLockingMutex::TryLock();}
			void Unlock(){return RecursiveLockingMutex::Unlock();}

			typename std::vector<Item>::iterator begin()
				{if (!RecursiveLockingMutex::TryLock()) ;
				return m_collection.begin();}
			typename std::vector<Item>::iterator end()
				{if (!RecursiveLockingMutex::TryLock()) ;
				return m_collection.end();}

			typename std::vector<Item>::size_type size(){ 
				return m_collection.size();}

			Item& operator[] (unsigned i){ return m_collection[i]; }

		protected:
			std::vector<Item> m_collection;
		};
	}
}
#endif